<template>
  <div class="projectBuildStup">
    <!--跳转上会界面-->
    <a-modal
      title="消息提醒"
      :visible="toDelVisible"
      :confirm-loading="false"
      @ok="toDelOk"
      @cancel="toDelVisible = false"
    >
      删除后将无法再查看该立项信息，确定删除？
    </a-modal>
    <a-modal
      title="消息提醒"
      :visible="confirmMeet"
      :confirm-loading="false"
      okText="需要上会"
      cancelText="不需要上会"
      @ok="needMeet"
      @cancel="notNeedMeet"
      :maskClosable="false"
      :closable="false"
    >
      请确认您的项目是否需要上会?
    </a-modal>
    <a-modal
      title="流程审批说明"
      :width="800"
      :visible="processAuditExplainShow"
      @ok="processAuditExplainShow = false"
      @cancel="processAuditExplainShow = false"
      :confirm-loading="false"
      :maskClosable="false"
      :closable="false"
      :zIndex="999999"
    >
      <template slot="footer">
        <a-button type="primary" @click="processAuditExplainShow = false">我已知悉</a-button>
      </template>
      <TApprovalTips v-if="projectBuild.projectClass == '10'"></TApprovalTips>
      <EApprovalTips v-if="projectBuild.projectClass == '20'"></EApprovalTips>
      <GcApprovalTips v-if="projectBuild.projectClass == '40' || projectBuild.projectClass == '41'"></GcApprovalTips>
      <HApprvalTips v-if="projectBuild.projectClass == '50'"></HApprvalTips>
      <MApprovalTips
        v-if="
          projectBuild.projectClass == '60' ||
          projectBuild.projectClass == '61' ||
          (projectBuild.projectClass == '62' && projectBuild.projectTypeSubCategory != 'MG') ||
          projectBuild.projectClass == '63' ||
          projectBuild.projectClass == '64'
        "
      ></MApprovalTips>
    </a-modal>
    <home-nav :userData="userinfo"></home-nav>
    <div class="navigator" style="display: flex">
      <div class="floatNav">
        <a-button v-if="submitAndDel && !isProjectMember" type="primary" @click="submitProject()" :loading="btnLoading">
          提交审批</a-button
        >
        <a-button
          v-if="submitAndDel && !isProjectMember"
          type="default"
          @click="toDelVisible = true"
          :loading="btnLoading"
          >删除项目</a-button
        >
        <a-button type="default" v-if="[1, 2].indexOf(pageId) > -1 && !isProjectMember" @click="showValHist"
          >历史版本
        </a-button>
        <a-button
          v-if="
            submitAndDel &&
            !isProjectMember &&
            ((projectBuild.projectClass == '40' && projectBuild.projectTypeSubCategory != 'S') ||
              (projectBuild.projectClass == '62' && projectBuild.projectTypeSubCategory != 'MG') ||
              ['10', '50', '61', '63', '64'].indexOf(projectBuild.projectClass) > -1)
          "
          type="default"
          @click="processAuditExplainShow = true"
          >流程说明</a-button
        >
      </div>
      <div :class="{ 'left-content': true, 'left-move200': !submitAndDel }">
        <ul>
          <li
            :class="{ clickShow: pageId == 8 }"
            style="background-color: #ff3b3b !important; border-color: #ff3b3b !important"
            @click="handleTogglePage(8)"
          >
            变更
          </li>

          <li
            v-for="(item, index) in tabs"
            :key="'tabs_' + index"
            :class="{ clickShow: pageId == parseInt(item.code) }"
            @click="handleTogglePage(parseInt(item.code))"
          >
            {{ item.name }}
          </li>
        </ul>
        <keep-alive>
          <router-view
            ref="routerpage"
            @routerCallBack="routerCallBack"
            @freshProjectBuildData="freshProjectBuildData"
            @freshChangeId="freshChangeId"
          />
        </keep-alive>
        
      </div>
      <div style="display:none">{{canDoSave}}</div>
      <div
        style="position: fixed; bottom: 10px; left: 0; width: 100%; display: flex; justify-content: center; z-index: 2"
        v-if="pageId < 8 && !isProjectMember"
      >
        <!-- <a-button
          v-if="pageId > 0 && !projectRewardApplyId"
          style="margin-right: 15px"
          class="default"
          @click="goPre()"
        >
          上一页面</a-button
        > -->
        <a-button
          v-if="[1, 2, 6, 7].indexOf(pageId) == -1 && canDoSave"
          style="margin-right: 15px; color: #fff; background: #1890ff"
          @click="savePage()"
          :loading="btnLoading"
          >保存本页
        </a-button>
        <a-button
          v-if="pageId === 5 && !!projectRewardApplyId"
          style="margin-right: 15px"
          class="default"
          @click="closeTab()"
          >关闭</a-button
        >
        <!-- <a-button
          v-if="
            ((!changeId && (showMeet == '1' ? pageId < 7 : pageId < 6)) ||
              (changeId && changeModels.indexOf(pageId) < changeModels.length - 1)) &&
            !projectRewardApplyId
          "
          class="default"
          @click="goNext()"
          >下一页面</a-button
        > -->
      </div>
    </div>
    <processUserSelect :columns="selUserCols" @selectUserConfirm="selectUserConfirm40" ref="processUserSelect" />
    <process-meet-select :columns="selMeetCols" @selectMeetConfirm="selectMeetConfirm" ref="processMeetConfirm" />
    <meet-reason-select @selectMeetReasonConfirm="selectMeetReasonConfirm" ref="meetReasonConfirm" />
  </div>
</template>
<script>
import Vue from 'vue'
import { ACCESS_TOKEN, USER_INFO } from '@/store/mutation-types'
import { getAction, postAction, getActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import { Modal } from 'ant-design-vue'
var autoSaveInterval = null
const processUsers = [
  {
    class: '10',
    users: [{ label: '部门A审批', field: 'presidentUser', username: '', realname: '', required: true }],
  },
  {
    class: '20',
    users: [{ label: '院/平台主管意见', field: 'managerUser', username: '', realname: '', required: true }],
  },
  {
    class: '20ec',
    users: [{ label: '平台主管', field: 'managerUser', username: '', realname: '', required: true }],
  },
  {
    class: '30',
    users: [
      { label: '专委主管', field: 'specialCommitteeUser', username: '', realname: '', required: true },
      { label: '相关负责人', field: 'projectControllingUser', username: '', realname: '', required: true },
      { label: '部门主管', field: 'deptManagerUser', username: '', realname: '', required: true },
      { label: '业务部门主管', field: 'businessManagerUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '40',
    users: [
      { label: '需求部门主管', field: 'deptManagerUser', username: '', realname: '', required: true },
      { label: '技术会审', field: 'technologyUser', username: '', realname: '', required: true },
      { label: '项目经理', field: 'projectManagerUser', username: '', realname: '', required: true },
      { label: '投资方', field: 'implementationDeptUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '40s',
    users: [
      { label: '需求部门主管', field: 'deptManagerUser', username: '', realname: '', required: true },
      { label: '技术会审', field: 'technologyUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '41',
    users: [
      { label: '事业部 子公司审批', field: 'companyLeaderUser', username: '', realname: '', required: true },
      { label: '技术会审', field: 'technologyUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '50',
    users: [
      { label: '投资部门班子A', field: 'deptManagerUser', username: '', realname: '', required: true },
      { label: '相关部门主管', field: 'techManagerUser', username: '', realname: '', required: true },
      { label: '投资委会审', field: 'financeDirectorUser', username: '', realname: '', required: true },
      { label: '主管领导', field: 'managerUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '60',
    users: [
      { label: '申请人主管', field: 'techDeptUser', username: '', realname: '', required: true },
      { label: '事业部/子公司财务', field: 'techManageUser', username: '', realname: '', required: true, maType: true },
    ],
  },
  {
    class: '61',
    users: [
      { label: '相关部门意见', field: 'departmentOpinionUser', username: '', realname: '', required: false },
      { label: '申请部门主管', field: 'departmentManagerUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '62',
    users: [
      { label: '相关部门意见', field: 'departmentOpinionUser', username: '', realname: '', required: false },
      { label: '申请部门主管', field: 'departmentManagerUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '62mg',
    users: [
      { label: '事业部/子公司负责人', field: 'techDeptUser', username: '', realname: '', required: true },
      { label: '科技管理部', field: 'techManageUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '63',
    users: [
      { label: '相关部门意见', field: 'departmentOpinionUser', username: '', realname: '', required: false },
      { label: '申请部门主管', field: 'departmentManagerUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '64',
    users: [
      { label: '经营体负责人', field: 'businessManagerUser', username: '', realname: '', required: true },
      { label: '会审', field: 'jointHearingUser', username: '', realname: '', required: true },
      { label: '董秘办审批', field: 'secretaryOfficeUser', username: '', realname: '', required: true },
      { label: '集团审批', field: 'groupAuditUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '64cancel',
    users: [
      { label: '申请部门', field: 'businessManagerUser', username: '', realname: '', required: true },
      { label: '专业部门会审', field: 'jointHearingUser', username: '', realname: '', required: true },
      { label: '董秘办', field: 'secretaryOfficeUser', username: '', realname: '', required: true },
    ],
  },
  {
    class: '65',
    users: [{ label: '部门主管', field: 'managerUser', username: '', realname: '', required: true }],
  },
  {
    class: '70',
    users: [{ label: '知识产权部主管审批', field: 'managerUser', username: '', realname: '', required: true }],
  },
  {
    class: '80',
    users: [{ label: '申请部门主管', field: 'deptManagerUser', username: '', realname: '', required: true }],
  },
]
const FTP_KEY = 'ftp'
import { UtilsMixin } from '@/mixins/UtilsMixin'
import { CodesMixin } from '@/mixins/CodesMixin'
export default {
  mixins: [UtilsMixin, CodesMixin],
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ProcessUserSelect: () => import('@/components/tools/ProcessUserSelect'),
    ProcessMeetSelect: () => import('@/components/tools/projectBuildStup/ProcessMeetSelect'),
    MeetReasonSelect: () => import('@/components/tools/projectBuildStup/MeetReasonSelect'),
    GcApprovalTips: () => import('@/views/approval/GcApprovalTips'),
    TApprovalTips: () => import('@/views/approval/TApprovalTips'),
    MApprovalTips: () => import('@/views/approval/MApprovalTips'),
    EApprovalTips: () => import('@/views/approval/EApprovalTips'),
    HApprvalTips: () => import('@/views/approval/HApprvalTips'),
  },
  data() {
    return {
      currUserId: this.$store.getters.userInfo.username,
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'projectBuildStup',
      },
      projectBuildData: {},
      projectBuildId: '',
      projectClass: '',
      projectType: '',
      showBugGet: true,
      projectBuild: {},
      notShowButGet: ['90'],
      url: {
        getProjectBuildVOWithProjectManagers: '/projectBuild/getProjectBuildVOWithProjectManagers',
        getProjectBuildTabShowStatus: '/projectBuild/getProjectBuildTabShowStatus',
        deleteById: '/projectBuild/deleteById',
        reloadQuesions: '/projectBuild/reloadQuesions',
        checkEngineBack: '/projectBuild/checkEngineBack',
        createProjectBuildMeet: '/projectBuild/projectBuildMeet/createProjectBuildMeet',
        publishEngineProject: '/projectBuild/publishEngineProject',
        calFlowNode40: '/projectBuild/calFlowNode40',
        updateSubmitParams: '/projectBuild/updateSubmitParams',
        checkPublishProject: '/projectBuild/checkPublishProject',
        checkProjectCycleRules: '/projectBuildTime/checkProjectCycleRules',
        getRequiredAttachCode: '/projectBuild/getRequiredAttachCode',
        getAttachInfo: '/tp/attach/getAttaches',
        getProjectBuildAttachCodeInfos: '/projectBuild/getProjectBuildAttachCodeInfos',
        queryChangeByBuildId: '/projectChange/queryByBuildId',
        codeInfo: '/manage/codeInfo/list',
        getProjectSubTable: '/projectBuildAudit/getProjectSubTable',
        queryChangeById: '/projectChange/queryById',
      },
      pageId: 8,
      showQuest: '',
      showCoreQuest: '',
      showMeet: '',
      currentAudit: 'false',
      toDelVisible: false,
      selMeetCols: [],
      selUserCols: [],
      rerunTestVisible: false,
      meet: {
        estimateMeetPersonUser: '',
        mainRemitter: '',
        joinRemitter: '',
        meetReason: '',
      },
      processDefinitionVersion: '',
      requiredAttachCode: [],
      attaches: [],
      requiredAttachCode: [],
      dengerTab: [],
      confirmMeet: false,
      btnLoading: false,
      changeModels: [],
      changePageIds: [],
      isProjectMember: false,
      changeId: '',
      processAuditExplainShow: false,
      processUserParams: {},
      projectRewardApplyId: '',
      confirmSavePage: -1,
    }
  },
  methods: {
    routerCallBack(val) {
      this.changeModels = []
      if (val != null) {
        this.changeModels = val.map((item) => (item = parseInt(item)))
        this.freshChangeModelToPageId()
      }
    },
    async submitProject() {
      this.dengerTab = []
      if (this.projectBuildId == null || this.projectBuildId == '') {
        this.$message.warning('请填写并保存基本信息')
        this.dengerTab.push('baseInfo')
        return
      }
      var res = false
      this.btnLoading = true
      if ([6, 7].indexOf(this.pageId) > -1) {
        res = true
      } else if (this.pageId == 0) {
        if (this.projectBuild != null && this.projectBuild.status > 1) {
          res = true
        } else {
          //基本信息
          var doSubmit = await this.$refs.routerpage.$children[0].doSubmit(true)
          console.log('doSubmit:', doSubmit)
          if (doSubmit.id != null && doSubmit.id.trim().length > 0) {
            //保存成功
            this.projectBuildId = doSubmit.id
            res = true
          }
        }
      } else {
        var doSubmit = await this.$refs.routerpage.doSubmit(true)
        console.log('doSubmit:', doSubmit)
        if (doSubmit == 2) {
          res = true
        }
      }
      this.btnLoading = false
      if (res) {
        //重跑价值表
        if (this.projectBuild.rerunTestFlag == 'true') {
          this.rerunTestVisible = true
          return
        }
        //检查必须上传附件
        var flag = false
        if (this.attaches != null) {
          for (var i = 0; i < this.attaches.length; i++) {
            var att = this.attaches[i]
            if (!flag) {
              flag = await this.checkAttach(att)
            }
          }
        }
        if (flag) {
          this.dengerTab.push('attach')
          return
        }
        getAction(this.url.getProjectBuildVOWithProjectManagers, { id: this.projectBuildId })
          .then((res) => {
            if (res.code == 200) {
              this.projectBuild = res.result
              this.projectClass = this.projectBuild.projectClass
              this.projectType = this.projectBuild.projectTypeSubCategory
              this.doSubmitProject()
            } else {
              this.$message.warning('提交检测-查询立项信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('提交检测-查询立项信息失败:' + res.message)
          })
      } else {
        var dengerT =
          this.pageId == 0
            ? 'baseInfo'
            : this.pageId == 1
            ? 'question'
            : this.pageId == 2
            ? 'coreQuestion'
            : this.pageId == 3
            ? 'time'
            : this.pageId == 4
            ? 'budget'
            : this.pageId == 5
            ? 'team'
            : ''
        this.dengerTab.push(dengerT)
      }
    },
    //操作提交
    async doSubmitProject() {
      if (!this.projectBuild.validResult) {
        this.$message.warning('请完整填写基本信息后，再进行提交')
        this.dengerTab.push('baseInfo')
        return
      }
      var vm = this
      this.btnLoading = true
      getAction(this.url.checkPublishProject, { id: this.projectBuildId })
        .then((res) => {
          vm.btnLoading = false
          if (res.code == 200) {
            vm.checkProjectCycleRules()
          } else {
            var msg = res.message
            if (msg != null) {
              var start = msg.split('_')[0].split('，')[1]
              if (start == 'baseInfo') {
                this.dengerTab.push('baseInfo')
              }
              if (start == 'value') {
                this.dengerTab.push('question')
              }
              if (start == 'budget') {
                this.dengerTab.push('budget')
              }
              if (start == 'time') {
                this.dengerTab.push('time')
              }
              if (start == 'team') {
                this.dengerTab.push('team')
              }
            }
            this.$message.warning('校验立项信息异常:' + msg.split('_')[1])
          }
        })
        .catch((res) => {
          this.$message.warning('校验立项信息异常:' + res.message)
        })
    },
    checkProjectCycleRules() {
      let vm = this
      getAction(this.url.checkProjectCycleRules, { projectBuildId: this.projectBuildId }).then((res) => {
        if (res.code == 200) {
          if (res.result && res.result !== '') {
            let checkResult = JSON.parse(res.result)
            const h = this.$createElement
            const m = checkResult.message.split('；')
            let html = []
            html.push(h('div', '按项目周期管理要求：'))
            m.forEach((item) => {
              html.push(h('div', item))
            })
            if (checkResult.forceCanNotSubmit) {
              this.$info({
                title: '周期规则校验结果',
                content: h('div', {}, html),
                onOk() {},
              })
            } else {
              html.push(h('div', '确定提交项目？'))
              Modal.confirm({
                title: '周期规则校验结果',
                content: h('div', {}, html),
                onOk() {
                  vm.doSubmitPro()
                },
                onCancel() {},
              })
            }
          } else {
            vm.doSubmitPro()
          }
        } else {
          this.$message.warning('校验项目周期规则异常:' + res.message)
        }
      })
    },
    doSubmitPro() {
      let vm = this
      if (vm.projectBuild.projectClass == '10') {
        //科技类直接问是否需上会
        vm.selectProcessUsers()
      } else {
        //配置需上会
        if (vm.projectBuild.needMeet) {
          if (vm.projectBuild.projectBuildMeet == null) {
            vm.selMeetCols = this.getMeetCols()
            vm.$refs.processMeetConfirm.doSelect()
          } else {
            //工程类提交审批需特殊处理
            if (
              (vm.projectBuild.projectClass == '40' && vm.projectBuild.projectTypeSubCategory != 'S') ||
              vm.projectBuild.projectClass == '41'
            ) {
              vm.calFlowNode40()
            } else {
              vm.selectProcessUsers()
            }
          }
          //配置无需上会
        } else {
          if (
            vm.projectBuild.projectClass == '40' &&
            vm.projectBuild.projectTypeSubCategory != 'S' &&
            vm.projectBuild.projectBuildMeet == null
          ) {
            vm.$refs.meetReasonConfirm.doSelect()
          } else {
            //工程类提交审批需特殊处理
            if (
              (vm.projectBuild.projectClass == '40' && vm.projectBuild.projectTypeSubCategory != 'S') ||
              vm.projectBuild.projectClass == '41'
            ) {
              vm.calFlowNode40()
            } else {
              vm.selectProcessUsers()
            }
          }
        }
      }
    },
    needMeet() {
      this.confirmMeet = false
      this.selMeetCols = this.getMeetCols()
      this.$refs.processMeetConfirm.doSelect()
    },
    notNeedMeet() {
      this.confirmMeet = false
      //工程类提交审批需特殊处理
      if (
        (this.projectBuild.projectClass == '40' && this.projectBuild.projectTypeSubCategory != 'S') ||
        this.projectBuild.projectClass == '41'
      ) {
        this.calFlowNode40()
      } else {
        this.selectProcessUsers()
      }
    },
    //检查必传附件
    async checkAttach(att) {
      var flag = false
      let ftpKey = new String(FTP_KEY)
      if (att.required) {
        //获取附件ftpKey
        let ftpRes = await getActionAsync(this.url.codeInfo, {
          type: this.projectBuild.projectTypeSubCategory + '类立项附件FTP',
          isDel: false,
          parentid: '1',
          code: att.code,
        })

        if (ftpRes.success) {
          if (ftpRes.result.records.length > 0) {
            ftpKey = ftpRes.result.records[0].name
          }
        }
        await getActionAsync(this.url.getAttachInfo, {
          dbKey: 'Trd',
          busKey: this.projectBuildId,
          busField: 'ProjectBuild',
          busType: att.code,
          ftpKey: ftpKey,
        }).then((res) => {
          if (res.data == null || res.data.length < 1) {
            this.$message.warning('【' + att.name + '】为必传附件类型，请至少上传一个')
            return (flag = true)
          }
        })
      }
      return flag
    },
    //上会确认
    selectMeetConfirm(cols) {
      var data = { projectBuildId: this.projectBuild.id, timeNodeCode: '1', needMeetReason: this.meet.meetReason }
      cols.forEach((col) => {
        data[col.field] = col.realname
      })
      var vm = this
      postAction(this.url.createProjectBuildMeet, data)
        .then((res) => {
          if (res.code == 200) {
            vm.projectBuild.projectBuildMeet = res.result
            vm.$message.success('保存上会成功', 1)
            //工程类提交审批需特殊处理
            if (
              (vm.projectBuild.projectClass == '40' && vm.projectBuild.projectTypeSubCategory != 'S') ||
              vm.projectBuild.projectClass == '41'
            ) {
              vm.calFlowNode40()
            } else {
              vm.selectProcessUsers()
            }
          } else {
            vm.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })
      return flag
    },
    //计算工程类立项流程节点信息
    calFlowNode40() {
      let vm = this
      getAction(vm.url.calFlowNode40 + '?projectId=' + vm.projectBuild.id).then((res) => {
        if (res.success) {
          vm.selUserCols = res.result
          vm.$refs.ProcessUserSelect.doSelect(res.result.fields, res.result.tips)
        } else {
          vm.$message.error('获取工程类立项流程节点信息失败:' + res.message)
        }
      })
    },
    //工程类上会原因确认
    selectMeetReasonConfirm(reason) {
      this.meet.meetReason = reason
      if (reason == '线上完成技术会审，不需要组织线下上会。') {
        if (this.projectBuild.projectTypeSubCategory != 'S') {
          this.checkEngineBack()
        } else {
          //工程类提交审批需特殊处理
          if (
            (this.projectBuild.projectClass == '40' && this.projectBuild.projectTypeSubCategory != 'S') ||
            this.projectBuild.projectClass == '41'
          ) {
            this.calFlowNode40()
          } else {
            this.selectProcessUsers()
          }
        }
      } else {
        //上会
        this.selMeetCols = this.getMeetCols()
        this.$refs.processMeetConfirm.doSelect()
      }
    },

    async get64SubTable() {
      let subTableType64 = ''
      await getAction(this.url.getProjectSubTable, { projectBuildId: this.projectBuild.id }).then((res) => {
        if (res.success && res.result && res.result.projectBuildCompany) {
          subTableType64 = res.result.projectBuildCompany.newOrChange
          return subTableType64
        }
      })
      return subTableType64
    },
    //调起流程选人，发起
    async selectProcessUsers() {
      var pclass = this.projectBuild.projectClass

      if (pclass == '20' && ['EC', 'ED'].includes(this.projectBuild.projectTypeSubCategory)) {
        pclass = '20ec'
      }

      //工程类 S子类设备制造天酿
      if (pclass == '40' && this.projectBuild.projectTypeSubCategory == 'S') {
        pclass = '40s'
      }

      // 外联咨询 mg
      if (pclass == '62' && this.projectBuild.projectTypeSubCategory == 'MG') {
        pclass = '62mg'
      }

      // 64MD cancel类型
      let subTableType64 = ''
      if (pclass == '64') {
        subTableType64 = await this.get64SubTable()
        console.log(subTableType64)
        if (subTableType64 == '注销法人公司') {
          pclass = '64cancel'
        }
        console.log(pclass)
      }

      //发起流程
      processUsers.forEach((item) => {
        if (pclass == item.class) {
          this.selUserCols = item.users
        }
      })
      //工程类
      if (this.projectBuild.projectClass == '40' && this.projectBuild.projectTypeSubCategory != 'S') {
        var engineVersion = this.checkEngineVersion(this.processDefinitionVersion)
        var versionNoNull = strNotNull(this.processDefinitionVersion)
        //版本号不为空，且<3
        if (strNotNull(this.meet.estimateMeetPersonUser)) {
          if (versionNoNull) {
            if (engineVersion > 2) {
              this.selUserCols.splice(2, 1)
            }
          } else {
            this.selUserCols.splice(2, 1)
          }
        }
        if (versionNoNull && engineVersion < 3) {
          this.selUserCols.splice(2, 1)
        }

        this.processAuditExplainShow = true
      }
      if (this.projectBuild.projectClass == '40' && this.projectBuild.projectTypeSubCategory != 'S') {
        this.processAuditExplainShow = true
      }
      /**
       * 投资项目审批：
       * 1、仅对于实业投资(projectTypeSubCategory-HA)，相关部门主管和主管领导需设置为非必选，且不要加星号
       * 2、股权投资(projectTypeSubCategory-HB)，（相关部门主管）必选 李军A
       */
      if (pclass == '50') {
        this.selUserCols.forEach((item) => {
          if (
            this.projectBuild.projectTypeSubCategory == 'HA' &&
            (item.field == 'techManagerUser' || item.field == 'managerUser')
          ) {
            item.required = false
          }
          if (this.projectBuild.projectTypeSubCategory == 'HB' && item.field == 'techManagerUser') {
            item.username = 'lij5'
            item.realname = '李军A'
          }
        })
      }
      //法人项目
      if (pclass == '64') {
        this.selUserCols = [
          { label: '经营体负责人', field: 'businessManagerUser', username: '', realname: '', required: true },
          {
            label: '会审',
            field: 'jointHearingUser',
            username: 'guanjh,liaoch,lij5',
            realname: '管江华,廖长辉,李军A',
            required: true,
          },
          { label: '董秘办审批', field: 'secretaryOfficeUser', username: 'zhangx', realname: '张欣', required: true },
          { label: '集团审批', field: 'groupAuditUser', username: 'zhangr', realname: '张蓉', required: true },
        ]
      }

      if (pclass == '64cancel') {
        this.selUserCols = [
          { label: '申请部门', field: 'businessManagerUser', username: '', realname: '', required: true },
          {
            label: '专业部门会审',
            field: 'jointHearingUser',
            username: 'liwp3,liangsp2,lij5,jianggw,guanjh',
            realname: '李文平,梁淑萍,李军A,蒋国伟,管江华',
            required: true,
          },
          { label: '董秘办', field: 'secretaryOfficeUser', username: 'zhangx', realname: '张欣', required: true },
        ]
      }
      //知识产权
      if (pclass == '70') {
        this.selUserCols = [
          { label: '知识产权部主管审批', field: 'managerUser', username: 'zhangr', realname: '张蓉', required: true },
        ]
      }
      // 包装材料研发-平面设计
      if (pclass == '80') {
        this.selUserCols = [
          { label: '申请部门主管', field: 'deptManagerUser', username: 'zhenglp', realname: '郑丽平', required: true },
        ]
      }
      if (pclass == '90') {
        this.selUserCols = [{ label: '申请人主管', field: 'DeptUser', username: '', realname: '', required: true }]
      }
      if (pclass == '60') {
        this.processUserParams = { maMoneyFlag: '1', deptId: this.projectBuild.mainDeptId }
      }
      this.$refs.processUserSelect.doSelect()
    },
    //检测工程版本
    checkEngineBack() {
      var vm = this
      getAction(this.url.checkEngineBack, { projectBuilId: this.projectBuild.id })
        .then((res) => {
          if (res.code == 200) {
            //回退
            vm.processDefinitionVersion = res.result
            //工程类提交审批需特殊处理
            if (
              (vm.projectBuild.projectClass == '40' && vm.projectBuild.projectTypeSubCategory != 'S') ||
              vm.projectBuild.projectClass == '41'
            ) {
              vm.calFlowNode40()
            } else {
              vm.selectProcessUsers()
            }
          } else {
            this.$message.warning('检测工程版本异常:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('检测工程版本失败:' + res.message)
        })
    },
    //匹配工程类流程版本
    checkEngineVersion(version) {
      //工程类版本控制匹配不上就是最新版本
      let versionList = this.projectBuild.hteProjectInitiateVersion.split(',')
      for (let i = 0; i < versionList.length; i++) {
        let j = i + 1
        if (!!versionList[j]) {
          if (versionList[i] <= version && version < versionList[j]) {
            return j
          }
        }
        if (j == versionList.length) {
          return j
        }
      }
    },
    //重跑价值表
    rerunConfirm() {
      var id = this.projectBuild.projectBuildId
      getAction(this.url.reloadQuesions, { id: id })
        .then((res) => {
          if (res.code == 200) {
            this.$router.push('/questionnairepage?projectBuildId=' + id)
          } else {
            this.$message.warning('重置价值表异常:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('重置价值表失败:' + res.message)
        })
    },
    selectUserConfirm40(cols) {
      if (cols && cols.length > 0) {
        postAction(this.url.updateSubmitParams + '?projectId=' + this.projectBuild.id, cols).then((res) => {
          if (res.success) {
            let params = []
            for (let col of cols) {
              let param = {}
              param.field = col.node
              param.username = col[col.node + 'Id']
              params.push(param)

              let param1 = {}
              param1.field = 'need' + col.node.slice(0, 1).toUpperCase() + col.node.slice(1)
              if (col.show == '1') {
                param1.username = '1'
              } else {
                param1.username = '0'
              }
              params.push(param1)
            }
            this.selectUserConfirm(params)
          } else {
            return this.$message.error('更新提交审批参数错误:' + res.message)
          }
        })
      }
    },
    selectUserConfirm(cols) {
      if (cols != null && cols.length > 0) {
        var data = {}
        cols.forEach((item) => {
          var key = item.field
          data[key] = item.username
        })
        if (this.projectBuild.projectClass == '40' && this.projectBuild.projectTypeSubCategory != 'S') {
          data.processDefinitionVersion = this.processDefinitionVersion
          var engineVersion = this.checkEngineVersion(this.processDefinitionVersion)
          var versionNoNull = strNotNull(this.processDefinitionVersion)
          //版本号不为空，且<3
          if (strNotNull(this.meet.estimateMeetPersonUser)) {
            if (versionNoNull) {
              if (engineVersion > 2) {
                data.technologyUser = this.meet.estimateMeetPersonUser
              }
            } else {
              data.technologyUser = this.meet.estimateMeetPersonUser
            }
          }
        }
        if (this.projectBuild.projectClass == '62' && this.projectBuild.projectTypeSubCategory == 'MG') {
          console.log()
          if (!data['techDeptUser'] && !data['leaderUser']) {
            this.$message.warning('[事业部/子公司总经理]与[主管领导]，至少选择一个')
            return
          }
        }
        let vm = this
        //参数组装完毕，发起流程
        postAction(this.url.publishEngineProject, { id: this.projectBuild.id, approvalPerson: data })
          .then((res) => {
            if (res.code == 200) {
              this.canEdit = false
              this.$message.success('发起审批流程成功')
              setTimeout(function () {
                window.location.href =
                  vm.HTE_OLD_SERVER_URL +
                  '/projectBuild/audit?id=' +
                  vm.projectBuild.id +
                  `&bootToken=${Vue.ls.get(ACCESS_TOKEN)}`
              }, 1000)
            } else {
              this.$message.warning('发起流程失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('发起流程异常:' + res.message)
          })
      } else {
        this.$message.warning('未选中操作员')
      }
    },
    getRequiredAttachCode() {
      getAction(this.url.codeInfo, { type: this.projectBuild.projectTypeSubCategory + '类必传附件' })
        .then((res) => {
          if (res.code == 200) {
            this.requiredAttachCode = res.result.records || []
            this.initAttaches()
          } else {
            this.$message.warning('查询必填附件失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询必填附件失败:' + res.message)
        })
    },
    //获取上会必选字段配置
    getMeetCols() {
      var cols = [
        {
          label: '选择预计上会人员',
          field: 'estimateMeetPerson',
          username: '',
          realname: '',
          required: true,
          min: 6,
          msg: '选择上会审核人，科技委成员至少选择一位，其余参会人员至少选择5位',
        },
      ]
      if (this.projectBuild.projectClass == '10') {
        cols[0].min = 1
        cols[0].msg = '至少选择3位主管上会评审，其中至少选择一名技术专业委成员'
        cols.push({
          label: '选择上会主汇报人',
          field: 'mainRemitter',
          username: '',
          realname: '',
          required: true,
          msg: '请选择有效的上会主汇报人',
        })
        cols.push({
          label: '选择上会汇报参与人',
          field: 'joinRemitter',
          username: '',
          realname: '',
          required: true,
          msg: '请选择有效的上会汇报参与人',
        })
      }
      if (this.projectBuild.projectClass == '20') {
        cols[0].min = 1
        cols[0].msg = '项目经理所在院（平台）主管，公司班子中分管主管，应用部门主管，核心项目成员'
      }
      if (this.projectBuild.projectClass == '40' && this.projectBuild.projectTypeSubCategory != 'S') {
        cols[0].min = 1
        cols[0].msg =
          '技术会审主要人员: 项目经理所在院（部）主管，工程委相关主管，科技相关主管（按需）和事业部相关主管（按需）'
      }
      return cols
    },

    toDelOk() {
      this.toDelVisible = false
      this.btnLoading = true
      getAction(this.url.deleteById, { id: this.projectBuildId })
        .then((res) => {
          this.btnLoading = false
          if (res.code == 200) {
            this.$message.success('删除项目成功:' + res.message)
            setTimeout(function () {
              this.$router.push('/homepage')
            }, 1500)
          } else {
            this.$message.warning('删除项目失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('删除项目异常:' + res.message)
        })
    },
    async getProjectBuild() {
      if (this.projectBuildId == null || this.projectBuildId == '') {
       return
      }
      var vm = this
      let res = await getActionAsync(this.url.getProjectBuildVOWithProjectManagers, {
        id: this.projectBuildId,
        changeId: this.changeId,
      })
      if (res.code == 200) {
        vm.projectBuild = res.result
        vm.projectClass = vm.projectBuild.projectClass
        vm.projectType = vm.projectBuild.projectTypeSubCategory
        //当前操作员是项目经理或副经理 在创建中都可以改
        if (vm.projectBuild.status < 2) {
          vm.autoSaveData()
        }
        vm.getRequiredAttachCode()
      } else {
        vm.$message.warning('查询立项信息失败:' + res.message)
      }
    },
    async autoSaveData() {
      var vm = this
      if ([6, 7, 8].indexOf(vm.pageId) > -1 || !vm.canDoSave) {
        return
      }
      if (autoSaveInterval != null) {
        clearInterval(autoSaveInterval)
      }
      autoSaveInterval = setInterval(async function () {
        console.log('------------------------auto save--------------------------------' + new Date())
        getAction('/projectBuild/pageFresh', {})
          .then((res) => {
            console.log('autoSaveData:' + JSON.stringify(res))
          })
          .catch((res) => {
            console.log('autoSaveData exception:' + JSON.stringify(res))
          })
      }, 1000 * 60 * 30)
    },
    async getProjectBuildTabShowStatus() {
      if (this.changeId) {
        return
      }
      await getActionAsync(this.url.getProjectBuildTabShowStatus, { id: this.projectBuildId })
        .then((res) => {
          if (res.code == 200) {
            var obj = res.result
            this.showQuest = obj.showQuest
            this.showCoreQuest = obj.showCoreQuest
            this.showMeet = obj.showMeet
          } else {
            this.$message.warning('判断价值表/上会是否显示失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('判断价值表/上会是否显示异常:' + res.message)
        })
    },
    async savePage() {
      this.btnLoading = true
      if (this.pageId == 0) {
        //基本信息
        this.handleTogglePage(0)
      } else {
        this.$refs.routerpage.doSubmit(true)
      }
      this.btnLoading = false
    },
    freshChangeModelToPageId() {
      this.changePageIds = []
      let idArr = [0, 1, 2, 3, 4, 5]
      idArr.forEach((id) => {
        var mid = id == 1 ? 2 : id == 2 ? 3 : id == 3 ? 1 : id
        if (this.changeModels.indexOf(mid) > -1) {
          this.changePageIds.push(id)
        }
      })
    },
    async goNext() {
      var goPageId = this.pageId
      if (this.changeId) {
        var index = this.changePageIds.indexOf(this.pageId) + 1
        goPageId = this.changePageIds[index]
      } else {
        if (this.pageId == 0 || this.pageId == 1) {
          if (this.showQuest == '1' && this.pageId == 0) {
            goPageId = 1
          } else if (this.showCoreQuest == '1') {
            goPageId = 2
          } else if (this.projectClass == '90') {
            goPageId = 5
          } else {
            goPageId = 3
          }
        } else {
          goPageId++
        }
      }
      await this.handleTogglePage(goPageId, true)
    },
    async goPre() {
      var goPageId = this.pageId
      if (this.changeId) {
        var index = this.changePageIds.indexOf(this.pageId) - 1
        goPageId = this.changePageIds[index]
      } else {
        if (this.pageId == 3 || this.pageId == 2) {
          if (this.showCoreQuest == '1' && this.pageId == 3) {
            goPageId = 2
          } else if (this.showQuest == '1') {
            goPageId = 1
          } else {
            goPageId = 0
          }
        } else {
          goPageId--
        }
      }
      await this.handleTogglePage(goPageId)
    },
    closeTab() {
      if (window.CloseCefTab) {
        window.CloseCefTab()
      } else {
        window.close()
      }
    },
    showValHist() {
      this.$refs.routerpage.showHist()
    },
    async handleTogglePage(index, flag) {
      if (isNaN(this.changeId) || this.changeId == 0) {
        this.confirmSave(index, flag)
        return
      }
      let res = false
      if ([6, 7].indexOf(this.pageId) > -1 || !this.canDoSave) {
        res = true
      } else if (this.pageId == 0) {
        //基本信息
        var doSubmit = await this.$refs.routerpage.$children[0].doSubmit()
        console.log('doSubmit:', doSubmit)
        if (doSubmit.id != null && doSubmit.id.trim().length > 0) {
          //保存成功
          this.projectBuildId = doSubmit.id
          await this.getProjectBuildTabShowStatus()
          if (flag) {
            if (this.showQuest == '1') {
              index = 1
            } else if (this.showCoreQuest == '1') {
              index = 2
            }
          }
          res = true
        }
      } else {
        if(!this.changeId){
          return this.$message.warning("请先保存变更页面")
        }
        var doSubmit = await this.$refs.routerpage.doSubmit(true)
        if (doSubmit == 1 || doSubmit == 2) {
          res = true
        }
      }
      var obj = {}
      switch (index) {
        case 0:
          obj = { path: '/projectChange/baseInfo', query: { projectType: this.projectType } }
          break
        case 1:
          obj = { path: '/projectChange/questionnairePage', query: {} }
          break
        case 2:
          obj = { path: '/projectChange/questionnaireCorePage', query: {} }
          break
        case 3:
          obj = { path: '/projectChange/timeForm', query: {} }
          break
        case 4:
          obj = { path: '/projectChange/budgetForm', query: {} }
          break
        case 5:
          obj = { path: '/projectChange/teamForm', query: {} }
          break
        case 6:
          obj = { path: '/projectChange/attachPage', query: { projectLevel: this.projectBuild.projectLevel } }
          break
        case 7:
          obj = { path: '/projectChange/meetingResults', query: { projectLevel: this.projectBuild.projectLevel } }
          break
        case 8:
          obj = { path: '/projectChange/changeRecord', query: {} }
      }
      if (res) {
        this.pageId = index
        obj.query.pageId = this.pageId
        obj.query.projectBuildId = this.projectBuildData.id
        obj.query.changeId = isNaN(this.changeId) ? 0 : this.changeId
        obj.query.projectClass = this.projectClass
        obj.query.currentAudit = this.currentAudit
        obj.query.canDoSave = this.canDoSave ? 'true' : 'false'
        obj.query.projectRewardApplyId = this.projectRewardApplyId
        this.$router.push(obj)
      } else {
        console.log('跳转失败')
      }
      this.confirmSavePage = -1
    },
    initAttaches() {
      var vm = this
      getAction(this.url.getProjectBuildAttachCodeInfos, {
        projectType: this.projectBuild.projectTypeSubCategory,
        timeNodeCode: '1',
      })
        .then((res) => {
          if (res.code == 200) {
            var result = res.result
            if (result != null) {
              result.forEach((item) => {
                if (vm.requiredAttachCode != null) {
                  vm.requiredAttachCode.forEach((reqAtt) => {
                    if (reqAtt.code == item.code) {
                      item.required = true
                    }
                  })
                }
                this.attaches.push(item)
              })
            }
          } else {
            this.$message.warning('查询附件字典配置失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询附件字典配置失败:' + res.message)
        })
    },
    getProjectChangeData() {
      if (!this.changeId) {
        return
      }
      let url = '',
        param = {}
      url = this.url.queryChangeById
      param = { id: this.changeId }
      getAction(url, param).then((res) => {
        if (res.result) {
          var changeContentList = res.result.changeContent ? res.result.changeContent.split(',') : []
          this.routerCallBack(changeContentList)
        }
      })
    },
    freshProjectBuildData(projectBuildData) {
      this.projectBuildData = projectBuildData
    },
    freshChangeId(changeId) {
      if (this.changeId != changeId) {
        this.changeId = changeId
        this.getProjectChangeData()
        // this.handleTogglePage(this.pageId, false)
      }
      this.changeId = changeId
    },
    confirmSave(index, flag) {
      let that = this
      Modal.confirm({
        title: '提示',
        content: '请确认是否保存变更单?',
        onOk() {
          that.confirmSavePage = that.pageId
          that.pageId = index
          that.routerpageSave(index, flag)
        },
        onCancel() {},
      })
    },
    async routerpageSave(index, flag) {
      await this.$refs.routerpage.save(true)
    },
  },
  mounted() {
    let types = []
    types.push('工程项目其他变更内容')
    this.fetchCodes(types)
    this.pageId = getParamValFromUrl('pageId')
    this.changeId = getParamValFromUrl('changeId')
    this.projectBuildId = getParamValFromUrl('projectBuildId')

    if (!this.changeId) {
      this.changeId = 0
    }
    if (this.pageId != null && this.pageId != '') {
      this.pageId = parseInt(this.pageId)
    } else {
      this.pageId = 8
    }
    this.getProjectChangeData()
    this.getProjectBuild()
  },
  computed: {
    tabs() {
      if (this.codes['工程项目其他变更内容'] && this.changeModels) {
        return this.codes['工程项目其他变更内容'].filter(
          (c) => c.parentid == '1' && c.additionalField=='1' && this.changeModels.indexOf(parseInt(c.code)) > -1
        )
      } else {
        return []
      }
    },
    submitAndDel() {
      //当前操作员是项目经理或副经理
      let data = this.projectBuild || {}
      var isManagerOrAssistantSub =
        (data.projectManagers && data.projectManagers.indexOf(this.currUserId) >= 0) ||
        (data.assistantProjectManagers &&data.assistantProjectManagers.indexOf(this.currUserId) >= 0)
      if (data.status == 1 && (data.createUserId == this.currUserId || isManagerOrAssistantSub)) {
        return true
      }
      return false
    },

    canDoSave() {
      //判断是否有编辑保存权限
      if (this.projectBuilId == null && this.projectBuilId == '') {
        return true
      }
      let data = this.projectBuild || {}
      var isManagerOrAssistant =
        (data.projectManagers && data.projectManagers.indexOf(this.currUserId) >= 0) ||
        (data.assistantProjectManagers&& data.assistantProjectManagers.indexOf(this.currUserId) >= 0) ||
        (data.projectMembers && data.projectMembers.indexOf(this.currUserId) >= 0) //项目成员可变更项目
      if (
        this.submitAndDel || //创建
        (this.currentAudit === 'true' && isManagerOrAssistant) || //审核
        (data.changeEditStatus) //变更
      ) {
        return true
      }
      return false
    },
  },
  destroyed() {
    if (autoSaveInterval != null) {
      clearInterval(autoSaveInterval)
    }
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  background-color: #1890ff !important;
}

.dengerBackGround {
  background-color: #faad14 !important;
}

.projectBuildStup {
  height: 100%;

  .navigator {
    min-height: 100%;
    padding: 40px 125px 0;
    background-color: #f5f5f5;

    .left-content {
      width: 100%;

      > ul {
        color: #fff;
        list-style: none;
        display: flex;
        background-color: #31a0e1;
        width: 100%;
        padding: 0;

        a {
          color: #fff;

          &:hover {
            color: #fff;
          }
        }

        li {
          padding: 10px 0px;
          cursor: pointer;
          position: relative;
          font-size: 15px;
          text-align: center;
          min-width: 7vw;

          &:hover {
            background-color: #0581ca;
          }

          &::before {
            content: ' ';
            color: #4fb1eb;
            position: absolute;
            width: 1px;
            height: 23px;
            border-left: 1px solid #4fb1eb;
            right: -1px;
          }
        }
      }
    }

    .clickShow {
      background-color: #0581ca;
      border-bottom: 1px solid #1890ff;
      cursor: pointer;
    }
  }
}

/deep/ .ant-table .ant-table-body::-webkit-scrollbar-track {
  background-color: #fff;
}

.floatNav {
  position: fixed;
  top: 180px;
  left: 30px;
  z-index: 1;

  > button {
    display: block;
    margin-bottom: 10px;
  }
}

@media (max-width: 1080px) {
  div.projectBuildStup .navigator {
    padding: 40px 30px 0;
  }

  .floatNav {
    left: 5px;

    > button {
      padding: 0 2px;
      font-size: 12px;
    }
  }
}
</style>
